﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;

namespace Microsoft.Bing
{
    /// <summary>
    /// An implementation of <see cref="ISearchStorage"/> which reads and writes the <see cref="SearchHistory"/> to and from isolated storage.
    /// </summary>
    public class IsolatedSearchStorage : ISearchStorage
    {
        private const string SEARCH_HISTORY_FILE = "Microsoft.SearchHistory.xml";

        #region ISearchStorage Members

        /// <summary>
        /// Reads an existing <see cref="SearchHistory"/> file from isolated storage.
        /// </summary>
        /// <returns>A <see cref="SearchHistory"/> collection</returns>
        public SearchHistory ReadHistory()
        {
            SearchHistory history = new SearchHistory();

            try
            {
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (file.FileExists(SEARCH_HISTORY_FILE))
                    {
                        using (FileStream stream = file.OpenFile(SEARCH_HISTORY_FILE, FileMode.Open))
                        {
                            XmlSerializer sr = new XmlSerializer(typeof(SearchHistory));
                            history = (SearchHistory)sr.Deserialize(stream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return history;
        }

        /// <summary>
        /// Writes an instance of <see cref="SearchHistory"/> to isolated storage.
        /// </summary>
        /// <param name="history">The <see cref="SearchHistory"/> instance to write to isolated storage.</param>
        public void WriteHistory(SearchHistory history)
        {
            try
            {
                if (history != null)
                {
                    using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (FileStream stream = file.OpenFile(SEARCH_HISTORY_FILE, FileMode.Create))
                        {
                            XmlSerializer sr = new XmlSerializer(typeof(SearchHistory));
                            sr.Serialize(stream, history);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        #endregion
    }
}
